package com.xudm.imp.service;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.xudm.imp.config.openai.MoonShotConfig;
import com.xudm.imp.utils.HttpClientUtil;
import org.apache.hc.core5.http.ParseException;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class MoonShotApi implements OpenAiApi {
    private final HttpClientUtil httpClientUtil;
    private final MoonShotConfig moonShotConfig;

    public MoonShotApi(HttpClientUtil httpClientUtil, MoonShotConfig moonShotConfig) {
        this.httpClientUtil = httpClientUtil;
        this.moonShotConfig = moonShotConfig;
    }

    @Override
    public JSONObject singleChat(String question) throws IOException, ParseException {
        String url = moonShotConfig.getUrl();
        String apiKey = moonShotConfig.getApiKey();
        String model = moonShotConfig.getModel();
        float temperature = moonShotConfig.getTemperature();

        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "Bearer " + apiKey);

        JSONArray messages = new JSONArray();
        JSONObject sysMessage = new JSONObject();
        JSONObject body = new JSONObject();
        sysMessage.put("role", "system");
        sysMessage.put("content", "你将收到一段用逗号或者顿号分隔的文本，你需要做的是把这些文本分割以后的词汇翻译成英文，多个单词使用小驼峰连接，然后给出符合这个变量的案例值，案例值可以包含中文。以此为基础组装成json对象，json对象的key是变量名，value是案例值。变量名不能含有中文，输出的时候只需要输出json对象即可。");

        JSONObject userMessage = new JSONObject();
        userMessage.put("role", "user");
        userMessage.put("content", question);

        messages.add(sysMessage);
        messages.add(userMessage);
        body.put("messages", messages);
        body.put("model", model);
        body.put("temperature", temperature);
        String result = httpClientUtil.sendPostRequest(url, body.toString(), headers);
        return new JSONObject(result);
    }
}
